<template>
  <a-button @click="clear">清空</a-button>
  <a-button @click="submit" type="primary">提交</a-button>
  <a-input v-model:value="title" placeholder="标题" />
  <a-input v-model:value="summary" placeholder="摘要" />
  <div>
    <a-upload
      v-model:file-list="fileListCover"
      :before-upload="beforeUpload"
      @remove="handleRemove"
      list-type="picture"
      class="upload-list-inline"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        上传封面
      </a-button>
    </a-upload>
  </div>
  <vue-markdown-editor class="editor" v-model="content" height="400px"></vue-markdown-editor>
</template>

<script setup lang="ts">
import type { UploadFile, UploadProps } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

import { ref } from 'vue'
import VueMarkdownEditor, { xss } from '@kangc/v-md-editor'
import { createBlog } from '@/http/blogs'
import { useRouter } from 'vue-router'
const router = useRouter()

// -- title 表示博客标题
// -- content 表示博客内容
// -- summary 表示博客摘要
// -- cover_image 表示博客封面图
// -- category_id 表示博客所属分类
// -- views 表示博客浏览量
// -- likes 表示博客点赞数
// -- status 表示博客状态（如草稿、已发布等）
const fileListCover = ref<UploadFile[]>([])

const content = ref('')
const title = ref('')
const summary = ref('')
const clear = () => {
  content.value = ''
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  fileListCover.value = [...(fileListCover.value || []), file]
  return false
}
const handleRemove: UploadProps['onRemove'] = (file) => {
  const index = fileListCover.value.indexOf(file)
  const newFileList = fileListCover.value.slice()
  newFileList.splice(index, 1)
  fileListCover.value = newFileList
}
const submit = () => {
  const html = xss.process(
    VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(content.value),
  )
  const formData = new FormData()
  formData.append('title', title.value)
  formData.append('content', html)
  formData.append('summary', summary.value)
  formData.append('status', '10')
  formData.append('file', fileListCover.value[0].originFileObj as File)

  createBlog(formData).then((res) => {
    content.value = '' // 清空编辑器内容
    title.value = '' // 清空标题
    summary.value = '' // 清空摘要
    router.replace('/')
  })
}
</script>
<style lang="scss" scoped>
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}
</style>
